# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

# from scrapy import signals


# class BaidunewsSpiderMiddleware(object):
#     # Not all methods need to be defined. If a method is not defined,
#     # scrapy acts as if the spider middleware does not modify the
#     # passed objects.
#
#     @classmethod
#     def from_crawler(cls, crawler):
#         # This method is used by Scrapy to create your spiders.
#         s = cls()
#         crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
#         return s
#
#     def process_spider_input(self, response, spider):
#         # Called for each response that goes through the spider
#         # middleware and into the spider.
#
#         # Should return None or raise an exception.
#         return None
#
#     def process_spider_output(self, response, result, spider):
#         # Called with the results returned from the Spider, after
#         # it has processed the response.
#
#         # Must return an iterable of Request, dict or Item objects.
#         for i in result:
#             yield i
#
#     def process_spider_exception(self, response, exception, spider):
#         # Called when a spider or process_spider_input() method
#         # (from other spider middleware) raises an exception.
#
#         # Should return either None or an iterable of Request, dict
#         # or Item objects.
#         pass
#
#     def process_start_requests(self, start_requests, spider):
#         # Called with the start requests of the spider, and works
#         # similarly to the process_spider_output() method, except
#         # that it doesn’t have a response associated.
#
#         # Must return only requests (not items).
#         for r in start_requests:
#             yield r
#
#     def spider_opened(self, spider):
#         spider.logger.info('Spider opened: %s' % spider.name)
#
#
# class BaidunewsDownloaderMiddleware(object):
#     # Not all methods need to be defined. If a method is not defined,
#     # scrapy acts as if the downloader middleware does not modify the
#     # passed objects.
#
#     @classmethod
#     def from_crawler(cls, crawler):
#         # This method is used by Scrapy to create your spiders.
#         s = cls()
#         crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
#         return s
#
#     def process_request(self, request, spider):
#         # Called for each request that goes through the downloader
#         # middleware.
#
#         # Must either:
#         # - return None: continue processing this request
#         # - or return a Response object
#         # - or return a Request object
#         # - or raise IgnoreRequest: process_exception() methods of
#         #   installed downloader middleware will be called
#         return None
#
#     def process_response(self, request, response, spider):
#         # Called with the response returned from the downloader.
#
#         # Must either;
#         # - return a Response object
#         # - return a Request object
#         # - or raise IgnoreRequest
#         return response
#
#     def process_exception(self, request, exception, spider):
#         # Called when a download handler or a process_request()
#         # (from other downloader middleware) raises an exception.
#
#         # Must either:
#         # - return None: continue processing this exception
#         # - return a Response object: stops process_exception() chain
#         # - return a Request object: stops process_exception() chain
#         pass
#
#     def spider_opened(self, spider):
#         spider.logger.info('Spider opened: %s' % spider.name)


import random
from baidunews.settings import USER_AGENTS_LIST

class RandomUserAgengtMiddleware(object):   #名字随便起，(object)不需要写
    def process_request(self,request,spider):
        userangent = random.choice(USER_AGENTS_LIST)
        request.headers["User-Agent"] = userangent  #添加自定义的UA，给request的headers赋值即可
        #这里不能return，数据通过这个直接到达下载器

class CheckUserAgent:   #检查每次User-Agent是否被调用
    def process_response(self,request,response,spider):
        # print(dir(response.request))  这里面是没有request的headers请求头里面的内容的
        print(request.headers["User-Agent"])
        return response #表示这个响应会通过引擎交给爬虫
        # return request 表示通过引擎交给调度器
        # 报错：scrapy.exceptions._InvalidOutput: Middleware CheckUserAgent.process_response must return Response or Request, got <class 'NoneType'>


class ProxyMiddleware(object):
    def process_request(self,request,spider):
        request.meta["proxy"] = "http://124.115.126.76:808" # 添加代理，需要在request的meta信息中添加proxy字段
                                                            # 代理的形式为：协议+IP地址+端口


"""
注意1：原middlewares.py可以删掉(有没有这个文件也不重要)，自己重新定义，名字可以随便起，只要在settings里面开启就可以
注意2：request是添加proxy的数据，这里添加代理添加键值
注意3：根据网站时http还是https，选择对应的代理ip（http还是https）
注意4：这里放一个ip地址是没有意义的，我们可以建立一个ip代理池：用一个程序测试ip是否可用，可用的存储下来，让scrapy去读取

注意5：request检验IP地址是否可用？？？
注意6：第三方ip，使用代理ip要加上用户名和密码（经过base64加密）
注意7：仍有问题，查看官方文档；如果出现异常，会交给后续的下载中间件（scrapy有很多）去处理，异常捕获（也可以自己捕获处理）


"""